Page({
  data: {
    knowledgeList: [],
    loading: true,
    page: 1,
    limit: 10,
    hasMore: true,
    searchText: '',
    activeCategory: '全部',
    categories: ['全部', '护肤', '彩妆', '香水', '美体']
  },

  onLoad: function () {
    // 加载第一页数据
    this.loadArticles()
  },
  
  // 加载文章列表
  loadArticles: function() {
    const { page, limit, activeCategory } = this.data
    const skip = (page - 1) * limit
    
    // 显示加载中
    wx.showLoading({
      title: '加载中',
    })
    
    // 处理标签筛选
    const tag = activeCategory !== '全部' ? activeCategory : null
    
    // 调用云函数获取文章列表
    wx.cloud.callFunction({
      name: 'getArticles',
      data: {
        limit,
        skip,
        tag
      }
    }).then(res => {
      console.log('云函数调用成功:', res)
      
      // 检查返回结果格式
      const result = res.result || {}
      if (result.success && Array.isArray(result.data)) {
        // 追加数据
        const list = page === 1 ? 
          result.data : 
          [...this.data.knowledgeList, ...result.data]
        
        // 处理数据，格式化日期和图片路径
        const knowledgeList = list.map(item => {
          try {
            // 安全提取日期
            let dateStr = '未知日期'
            if (item.publishDate) {
              if (typeof item.publishDate === 'string' && item.publishDate.length >= 10) {
                dateStr = item.publishDate.substring(0, 10)
              } else if (item.publishDate instanceof Date) {
                dateStr = item.publishDate.toISOString().substring(0, 10)
              }
            }
            
            // 安全提取内容摘要
            let description = '暂无描述'
            if (item.content) {
              description = item.content.replace(/<[^>]+>/g, '').substring(0, 30) + '...'
            }
            
            return {
              id: item._id,
              title: item.title || '无标题',
              description: description,
              coverImage: item.coverImage || '/images/default-cover.png',
              views: item.viewCount || 0,
              date: dateStr
            }
          } catch (err) {
            console.error('处理文章数据出错:', err, item)
            return null
          }
        }).filter(item => item !== null) // 过滤掉处理失败的项
        
        this.setData({
          knowledgeList,
          loading: false,
          hasMore: result.data.length === limit
        })
      } else {
        console.error('云函数返回格式错误:', result)
        this.setData({ loading: false })
        wx.showToast({
          title: '获取文章失败',
          icon: 'none'
        })
      }
    }).catch(err => {
      console.error('获取文章失败', err)
      this.setData({ loading: false })
      wx.showToast({
        title: '获取文章失败',
        icon: 'none'
      })
    }).finally(() => {
      // 确保隐藏加载提示
      wx.hideLoading()
      wx.stopPullDownRefresh()
    })
  },
  
  // 下拉刷新
  onPullDownRefresh: function() {
    this.setData({
      page: 1,
      hasMore: true
    })
    this.loadArticles()
  },
  
  // 上拉加载更多
  onReachBottom: function() {
    if (!this.data.hasMore) return
    
    this.setData({
      page: this.data.page + 1
    })
    this.loadArticles()
  },

  // 切换分类
  switchCategory: function(e) {
    const category = e.currentTarget.dataset.category
    if (category === this.data.activeCategory) return
    
    this.setData({
      activeCategory: category,
      page: 1,
      hasMore: true,
      knowledgeList: []
    })
    
    this.loadArticles()
  },
  
  // 搜索文章
  onSearch: function(e) {
    const searchText = e.detail.value
    this.setData({
      searchText,
      page: 1,
      hasMore: true,
      knowledgeList: []
    })
    
    this.loadArticles()
  },

  goToDetail: function (e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/knowledge-detail/knowledge-detail?id=' + id
    });
  }
}); 